package com.java.reggie.common;

import com.java.reggie.Controller.CommonController;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.FileNotFoundException;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 */
//@ControllerAdvice(annotations = {RestController.class,Controller.class})
@RestControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 异常处理方法
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        log.error(ex.getMessage());
        if (ex.getMessage().contains("Duplicate entry")) {
            return R.error("已存在");
        }
        return R.error("未知错误");
    }

    /**
     * 图片过大异常
     * @param ex
     * @return
     */
    @ExceptionHandler(FileSizeLimitExceededException.class)
    public R<String> exceptionHandler(FileSizeLimitExceededException ex){
        log.error("异常:"+ex.getMessage());
        if (ex.getMessage().contains("maximum permitted size of")){
            log.error("图片过大");
            return R.error("图片过大");
        }
        log.error("未知错误");
        return R.error("系统故障");
    }


    /**
     * 捕获自定义异常
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex) {
        log.error(ex.getMessage());
        return R.error(ex.getMessage());
    }
}
